package com.bank.controller;

import com.bank.constant.AccountType;
import com.bank.constant.MessageConstant;
import com.bank.dto.AccountDTO;
import com.bank.entity.Bill;
import com.bank.entity.Loan;
import com.bank.entity.User;
import com.bank.exception.UserNotFoundException;
import com.bank.result.Result;
import com.bank.service.*;
import com.bank.vo.AccountLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping("/account")
@Slf4j
@Api(tags = "2.账户管理")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private BillTransactionService billTransactionService;
    @Autowired
    private BillService billService;
    @Autowired
    private LoanService loanService;
    @Autowired
    private UserService userService;

    @GetMapping("/all")
    @ApiOperation("根据用户id获取所有账户信息")
    public Result<List<AccountLoginVO>> getAllAccountsByUserId(Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            throw new UserNotFoundException(MessageConstant.USER_NOT_FOUND);
        }

        // 查询账户信息
        List<AccountLoginVO> allAccounts = accountService.getAllAccountInfoByUserId(userId);

        // 查询bill, loan信息
        for (AccountLoginVO account : allAccounts) {
            Bill bill = billService.getBillByAccountId(account.getAccountId());
            if (account.getAccountType().equals(AccountType.CREDIT)) {
                Loan loan = loanService.getLoanByAccountId(account.getAccountId());
                BeanUtils.copyProperties(loan, account);
            }

            log.info("查询账户信息,accountId:{},bill:{}", account.getAccountId(), bill);

            BeanUtils.copyProperties(bill, account);
        }
        log.info("查询账户信息成功:{}", allAccounts);
        return Result.success(allAccounts, MessageConstant.ACCOUNT_QUERY_SUCCESS);
    }

    @PostMapping("/add")
    @ApiOperation("开户信息")
    @Transactional
    public Result<String> addAccount(@RequestBody @Valid AccountDTO accountDTO) {
        log.info("开户信息:{}", accountDTO);
        Long accountId = accountService.addAccount(accountDTO);
        log.info("开户成功,accountId:{}", accountId);
        billService.addBillByAccountId(accountDTO.getBalance(), accountId);

        if(accountDTO.getAccountType().equals(AccountType.CREDIT)){
            loanService.addLoanByAccountId(accountId);
        }

        return Result.success(MessageConstant.ACCOUNT_ADD_SUCCESS);
    }
}
